#include "afc_driver.h"
#include "qc.h"
#include "usart.h"
#include "tim.h"

int AFC_Send_and_Recv(uint8_t *send_buff, uint8_t send_len, uint8_t *recv_buff)
{
	AFC_Send_Ping(); // Send Master Ping
	if(AFC_Wait_Pin() != 0) return 0; // Wait Slave Ping
	AFC_Send_Data(send_buff, send_len); // Send Data and Master Ping
	if(AFC_Wait_Pin() != 0) return 0; // Wait Slave Ping
	
	send_len = AFC_Recv_Data(recv_buff);
	if(send_len != 0)
	{
		HAL_Delay_us(100);
		AFC_Send_Ping();
		AFC_Wait_Pin();
	}
	return send_len;
}

void AFC_CMD_Proc(uint8_t *data)
{
	switch(data[3])
	{
		case 0x00: // Shake Hand
			QC_Shake_Hand();
			HAL_Delay_ms(50);
			data[4] = AFC_Send_Ping();
			data[5] = 0;
			CMD_Response(data);
			break;
		case 0x01: // AFC Adjust Out
			data[5] = AFC_Send_and_Recv(data + 6, 1, data + 6);
			HAL_Delay_ms(30);
			data[5] = AFC_Send_and_Recv(data + 6, 1, data + 6);
			HAL_Delay_ms(30);
			data[5] = AFC_Send_and_Recv(data + 6, 1, data + 6);
            data[4] = 0;
			CMD_Response(data);
			break;
		case 0x02: // send custom data
            
			data[5] = AFC_Send_and_Recv(data + 6, data[5], data + 6);
			data[4] = 0;
            CMD_Response(data);
			break;
		default:
			break;
	}
}
